#include "webServer.h"
using namespace std;

WebServer::WebServer(){
    bzero(&serverAddr,sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serverAddr.sin_port = htons(8888);
};

WebServer::~WebServer(){
};

/*
 *socket的包裹函数
 */ 
int WebServer::Socket(int family, int type, int protocol){
    int sockfd;
    if((sockfd=socket(AF_INET, SOCK_STREAM, 0)) < 0)
        perror("socket error");
    cout<<sockfd<<endl;
    return sockfd;
};

/*
 *bind的包裹函数
 */ 
void WebServer::Bind(int &sockfd, const struct sockaddr *myaddr, socklen_t addrlen){
    if( bind(sockfd,myaddr,addrlen) < 0)
        perror("bind error");
    return ;
};

/*
 *listen的包裹函数
 */ 
void WebServer::Listen(int &sockfd, int backlog){
    char *ptr;
    if((ptr = getenv("LISTENQ")) != nullptr)
        backlog = atoi(ptr);

    if(listen(sockfd, backlog) < 0)
        perror("listen error");
    return ;
}

/*
 *accept的包裹函数
 */ 
int WebServer::Accept(int &sockfd, struct sockaddr *cliaddr, socklen_t *addrlen){
    int connfd;
    if( (connfd = accept(sockfd,cliaddr,addrlen)) < 0)
        perror("accept error");
    return connfd;
}

void WebServer::doMain(){
    int sockFd = Socket(AF_INET,SOCK_STREAM,0);
    socklen_t serLen = sizeof(serverAddr);
    Bind(sockFd,(const struct sockaddr*) &serverAddr,serLen);
    Listen(sockFd,10);
    
    while(1){
        socklen_t cliLen = sizeof(clientAddr);
        int connFd = Accept(sockFd, (struct sockaddr*) &clientAddr,&cliLen);
        if(fork() == 0){
            close(sockFd);

            char request[1024];
            recv(connFd,request,1024,0);
            request[strlen(request)+1]='\0';
            printf("%s\n",request);

            char buf[520]="HTTP/1.1 200 ok\r\nconnection: close\r\n\r\n";//HTTP响应
            int s = send(connFd,buf,strlen(buf),0);//发送响应
            // int fd = open("test.html",O_RDONLY);//消息体
            int fd = open("../www/hello.html",O_RDONLY);//消息体
            sendfile(connFd,fd,NULL,2500);//零拷贝发送消息体
            close(fd);
            close(connFd);
            exit(0);
        }
    }
    close(sockFd);
}